package com.whjz.dcfs.util;

import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SessionValidate extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		Map<String,Object> session = actionInvocation.getInvocationContext().getSession();

		ServletContext servletContext = ServletActionContext.getServletContext().getContext("/rais");
		if(servletContext!=null){
			Map<String,Object> sessionMap = (Map<String,Object>)servletContext.getAttribute("sessionMap");
			String jsessionid = CookieUtil.findCookie("JSESSIONIDALL",  ServletActionContext.getRequest());
			if(sessionMap!=null&&sessionMap.get(jsessionid)!=null){
				Object user = ((Map<String,Object>)sessionMap.get(jsessionid)).get("user");
				String concern = UserUtil.findUserFromSession(user, "getConcern");
				if(session.get("user")==null){
					session.put("user", user);
				}else{
					//判断权限是否相同，不同则覆盖
					Object oldUser = session.get("user");
					String oldConcern = UserUtil.findUserFromSession(oldUser, "getConcern");
					if(!oldConcern.equals(concern)){
						session.put("user", user);
					}
				}
				actionInvocation.invoke();
				return null;
			}else{
				if("XMLHttpRequest".equalsIgnoreCase(ServletActionContext.getRequest().getHeader("x-requested-with"))){  
				    ServletActionContext.getResponse().sendError(989);
				    return null;
				} 
			}
		}
		return "reLogin";
	}

}
